package com.ctgu.redislock03.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ctgu.redislock03.entity.VoucherEntity;
import com.ctgu.redislock03.mapper.VoucherMapper;
import com.ctgu.redislock03.service.VoucherService;
import com.ctgu.redislock03.utils.ApiResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

/**
* @author Alex2
* @description 针对表【t_voucher】的数据库操作Service实现
* @createDate 2025-03-07 17:44:43
*/
@Service
public class VoucherServiceImpl extends ServiceImpl<VoucherMapper, VoucherEntity>
    implements VoucherService {

    @Autowired
    @Qualifier("redisTemplateForObject")
    private RedisTemplate<String, Object> redisConfigForObject;

    private static final String REDIS_VOUCHER = "voucher:id:";

    @Override
    public ApiResult insertVoucher(VoucherEntity voucherEntity) {
        VoucherEntity voucher = lambdaQuery().eq(VoucherEntity::getName, voucherEntity.getName()).one();
        if (voucher != null) {
            return ApiResult.error("此种优惠券已存在，只能增加数量，无法再次插入");
        }
        boolean save = save(voucherEntity);
        if (!save) {
            return ApiResult.error("新增优惠券失败");
        }
        redisConfigForObject.opsForValue().set(REDIS_VOUCHER + voucherEntity.getId(), voucherEntity.getStock());
        return ApiResult.success("新增优惠券成功", voucherEntity);
    }
}




